package org.dromara.common.oss.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * oss 私有桶工具类
 * 用法：@JsonSerialize(using = OssUrlPrivateSerializer.class)
 * @author heyi
 * 2024/8/8
 */
@Component
public class OssUrlPrivateSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (StrUtil.isBlank(value)) {
            gen.writeString(StrUtil.EMPTY);
            return;
        }
        String[] imgs = value.split(StrUtil.COMMA);
        StringBuilder sb = new StringBuilder();
        OssClient instance = OssFactory.instance();

        for (String img : imgs) {
            // 解析文件名称
            String fileName = parseFileName(img);
            String privateUrl = instance.getPrivateUrl(fileName, 120);
            sb.append(privateUrl);
            sb.append(StrUtil.COMMA);
        }
        sb.deleteCharAt(sb.length() - 1);
        gen.writeString(sb.toString());
    }

    /**
     * 解析 文件名
     * @param img
     * @return
     */
    private static   String parseFileName(String img) {
        // http://124.223.36.202:9000/lxkprivate/2024/07/22/2cb538dce31b420e8619d542d73318c0.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20240808T094147Z&X-Amz-SignedHeaders=host&X-Amz-Credential=JQ919CX9TYY3PPQLO6M3%2F20240808%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Expires=120&X-Amz-Signature=5e0c9a75cff0a042481a0db47be6401058a6696f436836e58c5fd86f8a485a2c
        String  fileName= StringUtils.substringBefore(img, "?");
        fileName = StringUtils.substringAfter(fileName, "//");
        fileName = StringUtils.substringAfter(fileName, "/");
        fileName = StringUtils.substringAfter(fileName, "/");
        return fileName;
    }

}
